package com.project.servlet.student;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.project.bean.StudentBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;
import java.util.Locale;

public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //得到表单数据，封装成学生对象
        StudentBean student = new StudentBean();

        this.fullBean(req,student);

        resp.getWriter().println(student);
    }

    private void fullBean(HttpServletRequest req,Object beanObj){
        Class beanClass = beanObj.getClass();

        //得到请求参数名称枚举
        Enumeration<String> em = req.getParameterNames();
        while (em.hasMoreElements()){
            try {
                //取出枚举元素
                String str = em.nextElement();
                System.out.println(str);
                //根据表单名，得到表单值
                String value = req.getParameter(str);

                //根据属性名，得到书写对象
                Field f = beanClass.getDeclaredField(str);
                f.setAccessible(true);
                //给实体对象的属性赋值
                if (f.getType() == String.class){
                    f.set(beanObj,value);
                }else if (f.getType() == Integer.class || f.getType() == int.class){
                    f.set(beanObj,Integer.parseInt(value));
                }else if (f.getType() == LocalDate.class){
                    f.set(beanObj, LocalDate.parse(value));
                }
                else if (f.getType() == String[].class){
                    f.set(beanObj,req.getParameterValues(str));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
